package com.util;

import org.postgresql.jdbc3.Jdbc3PoolingDataSource;

import java.sql.*;

/**
 * Created by xudi on 2/9/16.
 */
public class JdbcTemplate {

    /**
     * 模板方法
     */
    public Object execute(StatementCallback action) {
        Connection conn = null;
        Statement st=null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            st=conn.createStatement();
            Object object=action.doInStatement(st);
            return object;
        } catch (SQLException err) {
            err.printStackTrace();
            free(rs, st, conn);
        }finally{
            free(rs, st, conn);
        }
        return null;
    }

    private Connection getConnection() {
        Connection conn = null;
        try {
            Jdbc3PoolingDataSource ds = new Jdbc3PoolingDataSource();
            ds.setServerName("121.41.18.253");
            ds.setPortNumber(5432);
            ds.setDatabaseName("customer");
            ds.setUser("luhuijun");
            ds.setPassword("Abc12345");
            ds.setInitialConnections(3);
            ds.setMaxConnections(20);
            conn = ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    private void free(ResultSet rs, Statement st, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
